package service

import (
	"context"
	"encoding/json"
	"fmt"
	"time"
	"videosS_rpc/basic/config"
	__ "videosS_rpc/basic/proto"
	"videosS_rpc/handler/model"
)

func (s *Server) VideosAdd(_ context.Context, in *__.VideosAddReq) (*__.VideosAddResp, error) {

	video := model.Videos{
		Title:        in.Title,
		Introduction: in.Introduction,
		Types:        int(in.Types),
		Permission:   int(in.Permission),
		VideoUrl:     in.VideoUrl,
		VideoCover:   in.VideoCover,
	}
	err := video.VideosAdd(config.DB)
	if err != nil {
		return nil, fmt.Errorf("内容信息提交失败")
	}
	marshal, err := json.Marshal(video)
	if err != nil {
		return nil, err
	}
	config.Rdb.Set(config.Ctx, "SortedKey", marshal, time.Hour)
	
	return &__.VideosAddResp{
		VideoId: int64(video.ID),
	}, nil
}
func (s *Server) VideosList(_ context.Context, in *__.VideosListReq) (*__.VideosListResp, error) {

	video := model.Videos{}
	list, err := video.VideosList(config.DB, int(in.Size), int(in.Page))
	if err != nil {
		return nil, err
	}
	marshal, err := json.Marshal(list)
	if err != nil {
		return nil, err
	}
	config.Rdb.Set(config.Ctx, "List", marshal, time.Minute)
	return &__.VideosListResp{
		List: list,
	}, nil
}

func (s *Server) IsVideosList(_ context.Context, in *__.IsVideosListReq) (*__.IsVideosListResp, error) {

	video := model.Videos{}
	list, err := video.IsVideosList(config.DB, int(in.Size), int(in.Page), in.Title, in.Introduction, in.VideoUrl, in.VideoCover)
	if err != nil {
		return nil, err
	}

	return &__.IsVideosListResp{
		List: list,
	}, nil
}

func (s *Server) IsVideosShow(_ context.Context, in *__.IsVideosShowReq) (*__.IsVideosShowResp, error) {

	video := model.Videos{}
	err := video.VideosShow(config.DB, int(in.Id))
	if err != nil {
		return nil, err
	}

	return &__.IsVideosShowResp{
		Title:        video.Title,
		Introduction: video.Introduction,
		Types:        int64(video.Types),
		Permission:   int64(video.Permission),
		VideoUrl:     video.VideoUrl,
		VideoCover:   video.VideoCover,
	}, nil
}
